import { useMemo, useState } from "react";
import { Button } from "antd-mobile";
import { UndoOutline } from "antd-mobile-icons";
import { useParams } from "react-router-dom";
import { useRequest } from "ahooks";

import { getEvaluateParam } from "@/api/product";

import Progress from "./components/progress";
import Question from "./components/question";

function ProductInfo() {
  // 获取 productId
  const { productId } = useParams();
  // 当前答题的下标
  const [curIdx, setCurIdx] = useState(0);
  // 答案收集    [['742'], ['1'], ['2', '3'], []]
  const [answers, setAnswers] = useState<string[][]>([]);

  // 获取 数据
  const { data } = useRequest(() => getEvaluateParam(productId!));

  // 组装问题列表
  const questions = useMemo(() => {
    const result: API.Iq[] = [];
    data?.itemList.forEach((item) => {
      result.push(...item.questions);
    });
    return result;
  }, [data]);

  console.log("questions", questions);
  console.log("answers", answers);

  // total
  const total = useMemo(() => {
    return questions.filter((item) => item.id !== "0").length;
  }, [questions]);

  // 重新选择
  const handleReset = () => {
    setAnswers([]);
    setCurIdx(0);
  };

  // 答题
  const handleSet = (keys: string[], index: number) => {
    // 修改 answers
    const newAnswers = [...answers];
    newAnswers[index] = keys;
    setAnswers(newAnswers);

    // 下一题
    setCurIdx(index + 1);
  };
  return (
    <div style={{ height: "100%", overflowY: "auto" }}>
      <Progress current={curIdx} total={total} />

      {questions.slice(0, curIdx + 1).map((item, index) => (
        <Question
          key={item.id}
          q={item}
          a={answers[index]}
          setA={(keys) => handleSet(keys, index)}
        />
      ))}

      <div
        style={{
          position: "fixed",
          width: "100%",
          height: 100,
          bottom: 0,
          left: 0,
          padding: "0 20px",
          boxSizing: "border-box",
          background: "#fff",
          display: curIdx >= total ? "flex" : "none",
          alignItems: "center",
        }}
      >
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            flexShrink: 0,
            marginRight: "20px",
          }}
          onClick={handleReset}
        >
          <UndoOutline />
          <span>重新选择</span>
        </div>
        <Button color="primary" block>
          查看预估价格
        </Button>
      </div>
    </div>
  );
}

export default ProductInfo;
